import React, { useEffect, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { DatePicker, Form, Input, InputNumber, Modal, Radio, Select, Upload, message } from 'antd';
import { updBattery } from '@/api/batteryApi'
import { getPowerStationList } from '@/api/powerStationApi'
import dayjs from 'dayjs';
// ==========================搜索远程数据代码==================================
let timeout: any;
let currentValue: any;
const fetchData = (value: any, callback: any) => {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;
  const fake = async () => {
    const { data } = await getPowerStationList()
    if (currentValue === value) {
      const res = data.filter((item: any) => (item.name.includes(currentValue) || item.powerStationId.includes(currentValue))).map((item: any) => ({
        value: item.
          powerStationId, text: `${item.name}(${item.
            powerStationId})`
      }));
      callback(res);
    }
  };
  if (value) {
    timeout = setTimeout(fake, 300);
  } else {
    fake()
  }
};
// ===============================================================================
const getBase64 = (img: any, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};
const App = (prpos: any) => {
  const { isModalOpen, setIsModalOpen, modelPrpos: { record, type }, Init } = prpos
  const [form] = Form.useForm();
  // ----------搜索远程数据代码-----------
  const [data, setData] = useState([]);
  const [value, setValue] = useState();
  const handleSearch = (newValue: any) => {
    fetchData(newValue, setData);
  };
  const handleChange = (newValue: any) => {
    setValue(newValue);
  };
  // ------------------------------------
  // ----------上传图片代码-----------
  const [imageUrl, setImageUrl] = useState(record?.picture);
  const [file, setFile] = useState('' as any);
  const handleUpload = () => {
    const formData = new FormData();
    formData.append('file', file);
    fetch(`http://120.55.191.224:8080/api/upload?id=${record._id}`, {
      method: 'POST',
      body: formData,
    })
  };
  // ------------------------------------
  useEffect(() => {
    if (type === '新增') {
      form.resetFields()
    } else {
      setImageUrl(record?.picture)
      fetchData(record?.powerStationId, setData);
      form.setFieldsValue({ ...record, warrantyEndDate: record?.warrantyEndDate ? dayjs(record.warrantyEndDate) : undefined })
    }
  }, [isModalOpen])
  const handleOk = async () => {
    const values = form.getFieldsValue();
    console.log(values);

    if (type === '新增') {
      // await addUser({ ...values })
    } else if (type === '编辑') {
      // ----------上传图片代码-----------
      handleUpload()
      if (imageUrl) {
        // 通过在图片链接后面加时间戳绕过浏览器缓存
        values.picture = `http://120.55.191.224:8080/static/${record._id}.png?time=${new Date().getTime()}`
      }
      // ------------------------------------
      await updBattery({ ...values, _id: record._id })
    }
    Init()
    message.success('操作成功');
    setIsModalOpen(false);
  };
  return (
    <>
      <Modal title={type} open={isModalOpen} onOk={handleOk} okText='确认' cancelText='取消' onCancel={() => setIsModalOpen(false)} forceRender>
        <Form form={form} layout='horizontal' wrapperCol={{ span: 16 }} labelCol={{ span: 4 }}>
          <Form.Item label="电池 ID" name="batteryId">
            <Input />
          </Form.Item>
          <Form.Item label="图片" name="picture">
            <Upload
              listType="picture-card"
              showUploadList={false}
              fileList={[file]}
              beforeUpload={(file: any) => {
                setFile(file);
                return false;
              }}
              onChange={(info) => {
                if (info.file.uid) {
                  getBase64(info.file, (url: any) => {
                    setImageUrl(url);
                  })
                }
              }}
              onRemove={() => {
                setImageUrl('');
                setFile('');
              }}
            >
              {imageUrl ?
                <img src={imageUrl} style={{ width: '100%', height: '100%', borderRadius: '8px' }} alt="avatar" /> :
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传</div>
                </button>}
            </Upload>
          </Form.Item>
          <Form.Item label="容量" name="capacity" >
            <InputNumber size='small' suffix="kWh" />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select options={[
              { value: '可用', label: <span>可用</span> },
              { value: '已租', label: <span>已租</span> },
              { value: '维修', label: <span>维修</span> },
            ]} />
          </Form.Item>
          <Form.Item label="所属电站" name="powerStationId">
            <Select
              showSearch
              value={value}
              defaultActiveFirstOption={false}
              suffixIcon={null}
              filterOption={false}
              onSearch={handleSearch}
              onChange={handleChange}
              onFocus={(e: any) => handleSearch(e.target.value)}
              notFoundContent={null}
              options={(data || []).map((d: any) => ({
                value: d.value,
                label: d.text,
              }))}
            />
          </Form.Item>
          <Form.Item label="质保日期" name="warrantyEndDate">
            <DatePicker placeholder='' />
          </Form.Item>
          <Form.Item label="是否已回收" name="isRecycled">
            <Radio.Group
              name="isRecycled"
              options={[
                { value: true, label: '已回收' },
                { value: false, label: '未回收' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default App;